package dcc.resources.code;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class EncryptDecrypt {

	public void encrypt(byte[] keyBytes, InputStream in, OutputStream out)
			throws Exception {
		DESKeySpec key = new DESKeySpec(keyBytes);
		SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = secretKeyFactory.generateSecret(key);
		Cipher ecipher;
		ecipher = Cipher.getInstance("DES");
		ecipher.init(Cipher.ENCRYPT_MODE, secretKey);
		out = new CipherOutputStream(out, ecipher);
		byte[] buf = new byte[1024];
		int numRead = 0;
		while ((numRead = in.read(buf)) >= 0) {
			out.write(buf, 0, numRead);
		}
		out.close();
	}

	public void decrypt(byte[] keyBytes, InputStream in, OutputStream out)
			throws Exception {
		DESKeySpec key = new DESKeySpec(keyBytes);
		SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = secretKeyFactory.generateSecret(key);
		Cipher dcipher;
		dcipher = Cipher.getInstance("DES");
		dcipher.init(Cipher.DECRYPT_MODE, secretKey);
		in = new CipherInputStream(in, dcipher);
		byte[] buf = new byte[1024];
		int numRead = 0;
		while ((numRead = in.read(buf)) >= 0) {
			out.write(buf, 0, numRead);
		}
		out.close();
	}

	public static void main(String[] args) throws Exception {

		EncryptDecrypt encrypter = new EncryptDecrypt();
		byte[] keyBytes = { 11, 23, 35, 57, 69, 71, 83, 95 };

		// 加密解密测试
//		encrypter.decrypt(keyBytes, new FileInputStream("导出的zip文件"),
//				new FileOutputStream("zip文件加密后保存为.pdb文件"));
		
		encrypter.decrypt(keyBytes, new FileInputStream("C:\\Users\\huayongj\\Desktop\\D20121229213051.pdb"),
				new FileOutputStream("C:\\Users\\huayongj\\Desktop\\d.zip"));
	}
}
